package lib.bone.admin.controller.system;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lib.bone.common.constant.CommonConst;
import lib.bone.common.core.domain.ResponseDTO;
import lib.bone.common.core.redis.RedisCache;
import lib.bone.system.domain.vo.CaptchaVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;


/**
 * @Author : Kindear
 * @Desc : 系统验证码控制器
 * @Date : 2021-11-25
 */
@Slf4j
@RestController
@RequestMapping("system")
@Api(tags = "图片验证码")
public class SysCaptchaController {
    /** 注入RedisCache 依赖 **/
    @Autowired
    RedisCache redisCache;


    @GetMapping(value = {"captchaImage","captcha"})
    @ApiOperation(value = "获取图片验证码",notes = "")
    public ResponseDTO getCaptcha(){

        /**
         * 1. 使用 HuTool 工具构建验证码 -- hutool 可以构建多种形式的验证码 ，此处选取较为简单的形式
         * 写入Redis Cache 中验证码信息 --
         */
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(116, 36,4,10);
        log.info("生成的图片验证码:"+lineCaptcha.getCode());
        // 生成和验证码对应的唯一UUID
        String uuid = IdUtil.randomUUID();
        // 将 uuid-code - 生命周期 存入Redis
        redisCache.setCacheObject(CommonConst.CAPTCHA_CODE_KEY.concat(uuid), lineCaptcha.getCode(), CommonConst.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setUuid(CommonConst.CAPTCHA_CODE_KEY.concat(uuid));
        captchaVO.setImg(lineCaptcha.getImageBase64Data());
        return ResponseDTO.succData(captchaVO);
    }

}
